<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { useAuthenticationStore } from 'my-vue-core/stores';
import { Token, User } from 'my-web-core/models';
import {
  AuthenticationService,
  CommonService,
  FormTextFieldValidator,
  RememberMeService,
  TokenService,
} from 'my-web-core/services';
import { onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';

import router from '../../app-router';
import AuthService from './auth-service';

const win: any = window as any;
const selectedFile = ref<String>();
const selectedFileIconData = ref<string>();

const route = useRoute();
const authenticationStore = useAuthenticationStore();
const ruleFormRef = ref<FormInstance>();
const count = ref<number>(0);

const ruleForm = reactive({
  username: authenticationStore.currentUsername,
  password: '',
  rememberMe: RememberMeService.rememberMe,
});

const rules = reactive({
  username: [
    {
      validator: (rule: any, value: any, callback: any) => {
        const errorMessage = new FormTextFieldValidator({
          label: '用户名',
          value: value,
        }).validate();

        errorMessage ? callback(new Error(errorMessage)) : callback();
      },
      trigger: 'change',
    },
  ],
  password: [
    {
      validator: (rule: any, value: any, callback: any) => {
        const errorMessage = new FormTextFieldValidator({
          label: '密码',
          value: value,
        }).validate();

        errorMessage ? callback(new Error(errorMessage)) : callback();
      },
      trigger: 'change',
    },
  ],
});

onMounted(() => {
  win.nativeAPI.onUpdateCounter((value: number) => (count.value = value));

  win.nativeAPI.sendAndGet((msg: string) => 'Response from render: ' + msg);
});

async function showOpenFileDialog(): Promise<void> {
  const files = await win.nativeAPI.showOpenFileDialog();

  if (files?.length > 0) {
    const iconData = await win.nativeAPI.extractFileIcon(files[0]);

    if (CommonService.isNotEmptyString(iconData)) {
      selectedFileIconData.value = `data:image/x-icon;base64,${iconData}`;
    }

    selectedFile.value = files[0];
  }
}

async function login(username: string, password: string, rememberMe: boolean): Promise<void> {
  const res = await new AuthService().login(username, password);

  if (res?.accessToken) {
    RememberMeService.rememberMe = rememberMe;

    // Gets the server data to user instance.
    const user = User.fromJSON(res);

    const authenticationService = new AuthenticationService();

    // Saves the user data retrieved from server.
    authenticationService.saveUserInfo(user);

    // Saves current username for next logic form auto fill input.
    authenticationService.saveCurrentUsername();

    // Gets the server data to token instance.
    const token = await Token.fromServerJSON(res);

    // Saves the token data retrieved from server.
    TokenService.saveToken(token);

    // Notifies change.
    authenticationStore.changeIsAuthenticated(AuthenticationService.isAuthenticated);
    authenticationStore.changeCurrentUser(AuthenticationService.currentUser);
    authenticationStore.changeCurrentUsername(AuthenticationService.currentUsername);

    const redirectTo = route.query.redirectTo?.toString() ?? '/home';

    // Once user logged in the login route will be replaced in the history stack.
    router.replace({ path: redirectTo });
  }
}

function submitForm(formEl: FormInstance | undefined): void {
  // if (!formEl) {
  //   return;
  // }

  formEl?.validate((valid) => {
    if (valid) {
      login(ruleForm.username!, ruleForm.password, ruleForm.rememberMe);
    }
  });
}
</script>

<template>
  <div class="container">
    <div class="form-container">
      <h2 class="title">平台管理系统</h2>
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="ruleForm.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
            placeholder="密码"
          />
        </el-form-item>
        <el-form-item prop="rememberMe">
          <el-checkbox v-model="ruleForm.rememberMe">记住我</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="full-width" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div>
      <div style="margin-top: 10px; margin-bottom: 10px">
        <el-button @click="showOpenFileDialog">Select File</el-button>
      </div>
      <div>
        <img v-if="selectedFileIconData" :src="selectedFileIconData" width="32" />
        {{ selectedFile }}
      </div>
    </div>
    <div>Count from native: {{ count }}</div>
  </div>
</template>

<style scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
}

.title {
  margin-top: 6px;
  align-self: center;
  margin-bottom: 10px;
}

.form-container {
  display: flex;
  flex-direction: column;
  width: 400px;
  background-color: #dcdcdc;
  margin-top: 180px;
  padding: 10px;
}

.form-button {
  width: 100%;
}
</style>
